<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { listen } from '@tauri-apps/api/event'
import { writeText } from '@tauri-apps/plugin-clipboard-manager'
import { useClipboardStore } from '../stores/clipboard'
import { useSettingsStore } from '../stores/settings'
import ClipboardEditor from '../components/ClipboardEditor.vue'
import { formatTime } from '../utils/timeUtils'

interface ClipboardItem {
  id: number
  content: string
  timestamp: number
  favorite: boolean
}

const clipboardStore = useClipboardStore()
const settingsStore = useSettingsStore()
const showEditor = ref(false)
const selectedItem = ref<ClipboardItem | null>(null)
const searchQuery = ref('')
const filterType = ref('all')
const showConfirmModal = ref(false)

const filteredItems = computed(() => {
  let items = clipboardStore.items
  
  // 先根据筛选类型过滤
  switch (filterType.value) {
    case 'favorite':
      items = items.filter(item => item.favorite)
      break
    case 'normal':
      items = items.filter(item => !item.favorite)
      break
  }
  
  // 再根据搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    items = items.filter(item => 
      item.content.toLowerCase().includes(query)
    )
  }
  
  return items
})

onMounted(async () => {
  // 加载历史记录
  await clipboardStore.loadClipboardItems()
  
  // 监听搜索框聚焦事件
  const searchUnlisten = await listen('focus-search', () => {
    const searchInput = document.querySelector('input[type="text"]') as HTMLInputElement
    if (searchInput) {
      searchInput.focus()
    }
  })
  

  // 清理事件监听
  onUnmounted(async () => {
    await searchUnlisten()
  })
})

const copyToClipboard = async (text: string) => {
  await writeText(text)
}

const openEditor = (item: ClipboardItem) => {
  selectedItem.value = item
  showEditor.value = true
}

const closeEditor = () => {
  selectedItem.value = null
  showEditor.value = false
}

const toggleFavorite = async (item: ClipboardItem) => {
  await clipboardStore.updateItem({
    id: item.id,
    content: item.content,
    timestamp: item.timestamp,
    favorite: !item.favorite
  })
}

const clearAll = () => {
  clipboardStore.clearAll()
}

const clearFavorites = () => {
  showConfirmModal.value = true
}

const confirmClearFavorites = () => {
  clipboardStore.clearFavorites()
  showConfirmModal.value = false
}

const removeItem = (id: number) => {
  clipboardStore.deleteItem(id)
}

const toggleFilter = (type: string) => {
  filterType.value = filterType.value === type ? 'all' : type
}
</script>

<template>
  <div class="flex flex-col h-full bg-base-100">
    <!-- 标题栏 -->
    <header class="flex-none border-b border-base-200 bg-base-100/80 backdrop-blur-md sticky top-0">
      <div class="px-4 py-3">
        <div class="flex justify-between items-center">
          <div class="flex items-center gap-2">
            <div class="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center">
              <i class="ri-clipboard-line text-primary text-xl"></i>
            </div>
            <div>
              <h2 class="text-lg font-bold">剪贴板历史</h2>
              <p class="text-xs text-base-content/60">
                共 {{ clipboardStore.items.length }}/{{ settingsStore.maxItems }} 条记录
              </p>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <div class="join">
              <button 
                class="btn btn-sm join-item"
                :class="{ 'btn-active': filterType === 'all' }"
                @click="filterType = 'all'"
              >
                全部
              </button>
              <button 
                class="btn btn-sm join-item"
                :class="{ 'btn-active': filterType === 'favorite' }"
                @click="toggleFilter('favorite')"
              >
                <i class="ri-star-fill mr-1" :class="{ 'text-yellow-400': filterType === 'favorite' }"></i>
                收藏
              </button>
              <button 
                class="btn btn-sm join-item"
                :class="{ 'btn-active': filterType === 'normal' }"
                @click="toggleFilter('normal')"
              >
                <i class="ri-clipboard-line mr-1"></i>
                普通
              </button>
            </div>
            <div class="join">
              <button 
                @click="clearAll" 
                class="btn btn-sm join-item btn-error"
                title="清空全部"
              >
                <i class="ri-delete-bin-line mr-1"></i>
                清空普通
              </button>
              <button 
                @click="clearFavorites" 
                class="btn btn-sm join-item btn-warning"
                title="清空收藏"
              >
                <i class="ri-star-line mr-1"></i>
                清空收藏
              </button>
            </div>
          </div>
        </div>

        <div class="form-control mt-3" v-if="clipboardStore.items.length > 0">
          <div class="relative flex items-center">
            <div class="absolute left-3 text-base-content/60">
              <i class="ri-search-line"></i>
            </div>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索剪贴板内容..."
              class="input input-bordered input-sm w-full pl-9 pr-9 bg-base-200/50"
            />
            <button 
              class="absolute right-3 text-base-content/60 hover:text-base-content"
              v-if="searchQuery"
              @click="searchQuery = ''"
            >
              <i class="ri-close-line"></i>
            </button>
          </div>
        </div>
      </div>
    </header>
    
    <main class="flex-1 relative">
      <div class="absolute inset-0 overflow-y-auto custom-scrollbar">
        <div class="max-w-3xl mx-auto px-4 py-4">
          <div class="space-y-2">
            <div v-if="clipboardStore.items.length === 0" 
                 class="card bg-base-200 text-center py-12">
              <div class="w-16 h-16 mx-auto rounded-2xl bg-base-300/50 flex items-center justify-center mb-4">
                <i class="ri-clipboard-line text-4xl text-base-content/40"></i>
              </div>
              <p class="text-sm text-base-content/60">暂无剪贴板历史记录</p>
              <p class="text-xs text-base-content/40 mt-1">复制内容后将自动记录在这里</p>
            </div>
            
            <div v-else-if="filteredItems.length === 0" 
                 class="card bg-base-200 text-center py-12">
              <div class="w-16 h-16 mx-auto rounded-2xl bg-base-300/50 flex items-center justify-center mb-4">
                <i class="ri-file-search-line text-4xl text-base-content/40"></i>
              </div>
              <p class="text-sm text-base-content/60">未找到匹配的记录</p>
              <p class="text-xs text-base-content/40 mt-1">尝试使用其他关键词搜索</p>
            </div>

            <div v-else v-for="item in filteredItems" 
                 :key="item.id" 
                 class="group relative bg-base-200 hover:bg-base-300/50 rounded-lg transition-all duration-300"
                 @dblclick.self="openEditor(item)">
              <div class="p-3" @dblclick.stop>
                <div class="flex items-start gap-3">
                  <div class="flex-none" v-if="item.favorite">
                    <i class="ri-star-fill text-yellow-400"></i>
                  </div>
                  <div class="flex-1 min-w-0" @dblclick.stop="openEditor(item)">
                    <p class="text-sm font-mono break-all max-h-10 overflow-hidden">{{ item.content }}</p>
                    <div class="flex items-center gap-3 mt-2 text-xs text-base-content/60">
                      <span>{{ formatTime(item.timestamp) }}</span>
                      <span class="opacity-0 group-hover:opacity-60">双击编辑</span>
                    </div>
                  </div>
                  <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button 
                      class="btn btn-ghost btn-sm btn-square tooltip tooltip-left" 
                      data-tip="复制"
                      @click.stop="copyToClipboard(item.content)"
                    >
                      <i class="ri-file-copy-line"></i>
                    </button>
                    <button 
                      class="btn btn-ghost btn-sm btn-square tooltip tooltip-left" 
                      :data-tip="item.favorite ? '取消收藏' : '收藏'"
                      @click.stop="toggleFavorite(item)"
                    >
                      <i class="ri-star-fill" :class="{ 'text-yellow-400': item.favorite }"></i>
                    </button>
                    <button 
                      class="btn btn-ghost btn-sm btn-square tooltip tooltip-left text-error" 
                      data-tip="删除"
                      @click.stop="removeItem(item.id)"
                    >
                      <i class="ri-delete-bin-line"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <div v-if="showConfirmModal" class="fixed inset-0 flex items-center justify-center z-50">
      <!-- 背景遮罩 -->
      <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" @click="showConfirmModal = false"></div>
      
      <!-- 对话框 -->
      <div class="bg-base-100 rounded-lg shadow-lg w-80 p-4 relative z-10">
        <h3 class="font-bold text-lg">确认清空收藏</h3>
        <p class="py-4 text-sm text-base-content/80">确定要清空所有收藏的内容吗？此操作无法撤销。</p>
        <div class="flex justify-end gap-2">
          <button 
            class="btn btn-sm btn-ghost"
            @click="showConfirmModal = false"
          >
            取消
          </button>
          <button 
            class="btn btn-sm btn-error"
            @click="confirmClearFavorites"
          >
            确认清空
          </button>
        </div>
      </div>
    </div>

    <ClipboardEditor
      v-if="showEditor"
      :item="selectedItem || { id: 0, content: '', timestamp: Date.now(), favorite: false }"
      @close="closeEditor"
      @save="clipboardStore.updateItem"
    />
  </div>
</template>

<style scoped>
.card {
  @apply hover:bg-base-300/50;
}

.btn-ghost {
  @apply hover:bg-base-300;
}

.btn-ghost:hover {
  @apply bg-base-content/10;
}

input.input {
  @apply bg-base-200 border-base-300 focus:outline-none focus:border-primary/50;
}

.ri-search-line,
.ri-close-line {
  @apply text-lg;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: hsl(var(--p)/0.2) transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  @apply bg-transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  @apply bg-primary/20 rounded-full hover:bg-primary/40 transition-colors;
}

.btn-square {
  @apply w-8 h-8 min-h-0;
}

.join .btn-active {
  @apply bg-base-300;
}

.tooltip::before {
  @apply text-xs;
}
</style> 